<?php

namespace App\Services\Aliyun\Sms;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use App\Services\Aliyun\BaseService;
use App\Services\Configs\DefaultService;

class AliYunSmsServices extends BaseService
{
    /**
     * 发送短信验证码
     * @param $phone：手机号码
     * @param $code：验证码
     */
    public static function sendSmsCode($phone, $code)
    {
        $config = self::getConfig(DefaultService::ALI_SMS);
        $templateParam = json_encode(['code' => $code]);

        try {
            AlibabaCloud::accessKeyClient($config['AccessKeyId'], $config['AccessKeySecret'])
                ->regionId($config['regionId']) // replace regionId as you need
                ->asDefaultClient();

            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                ->scheme('https://dysmsapi.aliyuncs.com/') // https | http
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->options([
                    'query' => [
                        'PhoneNumbers' => $phone,
                        'SignName' => $config['SignName'],
                        'TemplateCode' => $config['TemplateCode'],
                        'TemplateParam' => $templateParam,
                        'RegionId' => $config['regionId'],
                    ],
                ])
                ->request();
            //var_dump($result->toArray());die;

            $data = $result->toArray();
            if ($data['Code'] == 'OK') {//发送成功
                return 1;
            } else { //发送失败
                return $result->toArray();
            }
        } catch (ClientException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        } catch (ServerException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        }
    }
}
